const { result ,isNumber,parseArrayString} = require("common-utils");
const uniID=require("uni-id-common");
const db = uniCloud.database();
const dbCmd = db.command;
module.exports = {
	_before:async function () { // 通用预处理器
		this.httpInfo = this.getHttpInfo();		
		let {httpMethod="GET",headers:{token},queryStringParameters=null,body=null} = this.httpInfo
		this.httpMethod = httpMethod.toUpperCase();		
		this.queryStringParameters = queryStringParameters;
		this.body = body ? JSON.parse(body) : null;
		if(!token) throw result({code:401,msg:"required",custom:"必须传递token"});
		const clientInfo = this.getClientInfo()
		const uniIDIns = uniID.createInstance({
			clientInfo
		})	
		let {errCode,uid,exp} =  await uniIDIns.checkToken(token);
		this.uid = uid;
		if(errCode == 'uni-id-check-token-failed') throw result({code:403,msg:"error",custom:"token校验未通过"});
		if(errCode == 'uni-id-token-expired') throw result({code:401,msg:"error",custom:"token已失效"});		
	},
	//获取分类列表
	async classify({pageNum=1,pageSize=8,select=false}={}){
		try{
			if(this.httpMethod!="GET") return result({code:400,msg:"error",custom:"method类型需要GET"});
			select = select === "true";		
			pageSize = select ? 8 : pageSize>50 ? 50 : Number(pageSize);
			if(select) pageNum=1;
			let skipNum = (pageNum-1) * pageSize;	
			let whereObj = {is_delete:dbCmd.neq(true)};
			if(select) whereObj.select = true;				
			let res1 = db.collection("xxm-bizhi-category")
			.where(whereObj)
			.orderBy("sort","asc")
			.skip(skipNum)
			.limit(pageSize)		
			.get();		
			
			let res2  = db.collection("xxm-bizhi-category").where(whereObj).count();		
			let res = await Promise.all([res1,res2]);		
			return result({code:200,msg:"success",data:res[0].data,total:res[1].total});
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});			
		}	
		
	},
	//添加分类
	async addClassify(){	
		try{			
			if(this.httpMethod!="POST") return result({code:400,msg:"error",custom:"method类型需要POST"});
			let {name,sort,picurl,description,select=false,enable=true} = this.body;
			if(!name) return result({code:400,msg:"required",custom:"必须传递name"});
			if(!sort) return result({code:400,msg:"required",custom:"必须传递sort"});
			if(isNaN(sort)) return result({code:400,msg:"error",custom:"sort值需要为number类型"});
			sort = Number(sort);
			select = select === "true";				
			let res = await db.collection("xxm-bizhi-category").add({
				user_id:this.uid,
				name,
				sort,
				picurl,
				description,
				select,
				enable,
				createTime:Date.now()
			})
			return result({code:200,msg:"success",data:res});
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});			
		}			
	},
	//删除分类
	async removeClassify(){
		try{			
			if(this.httpMethod!="DELETE") return result({code:400,msg:"error",custom:"method类型需要DELETE"});
			let {ids} = this.body;
			if(!ids) return result({code:400,msg:"required",custom:"必须传递ids"});
			
			let res = await db.collection("xxm-bizhi-category").where({
				_id:dbCmd.in(ids)
			}).update({
				is_delete:true
			})
			if(res.updated) return result({code:200,msg:"success"});
			return result({code:400,msg:"error"});
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});			
		}
	},
	//修改分类
	async updateClassify(){
		try{
			if(this.httpMethod!="POST") return result({code:400,msg:"error",custom:"method类型需要POST"});
			let {id,name,sort,picurl,description,select=false,enable=true} = this.body;	
			if(!id) return result({code:400,msg:"required",custom:"必须传递id"});
			if(!name) return result({code:400,msg:"required",custom:"必须传递name"});
			if(!sort) return result({code:400,msg:"required",custom:"必须传递sort"});
			if(isNaN(sort)) return result({code:400,msg:"error",custom:"sort值需要为number类型"});
			sort = Number(sort);
			select = select === "true";	
			let res = await db.collection("xxm-bizhi-category").doc(id).update({			
				name,
				sort,
				picurl,
				description,
				select,
				enable,
				createTime:Date.now()
			})
			if(res.updated) return result({code:200,msg:"success"});
			return result({code:400,msg:"error"});
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});			
		}
	},
	
	//壁纸列表
	async paper({pageNum=1,pageSize=8,keyword,classid,order="createTime"}={}){	
		try{
			if(this.httpMethod!="GET") return result({code:400,msg:"error",custom:"method类型需要GET"});
			pageSize = pageSize>50 ? 50 : Number(pageSize);		
			let skipNum = (pageNum-1) * pageSize;		
			let screen = {is_delete:dbCmd.neq(true)};
			if(keyword) screen.description = new db.RegExp({
				regex: keyword,
				options: 'i',
			});
			if(classid) screen.classid = classid;		
			let res1 = db.collection("xxm-bizhi-paper")
			.where(screen)
			.orderBy(order,"desc")
			.skip(skipNum)
			.limit(pageSize)		
			.get();		
			let res2 = db.collection("xxm-bizhi-paper").where(screen).count();		
			let res = await Promise.all([res1,res2]);
			return result({code:200,msg:"success",data:res[0].data,total:res[1].total});	
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});			
		}
	},
		
	
	//批量新增壁纸
	async addPapers(){			
		try{
			if(this.httpMethod!="POST") return result({code:400,msg:"error",custom:"method类型需要POST"});			
			let {arrs} = this.body;
			if(!Array.isArray(arrs) || !arrs.length) return result({code:400,msg:"error",custom:"arrs值需要为array类型，并不能为空"});		
			for (let item of arrs) {
				if(!item.classid) return result({code:400,msg:"required",custom:JSON.stringify(item)+",该项缺少classid"});
				if(!item.picurl) return result({code:400,msg:"required",custom:JSON.stringify(item)+",该项缺少picurl"});
				if(!item.score) item.score = 5; 
				if(isNaN(item.score)) return result({code:400,msg:"error",custom:JSON.stringify(item)+",score值需要为number类型"});
				item.score = Number(item.score);
				if(!item.tabs) item.tabs = [];
				if(!Array.isArray(item.tabs)) return result({code:400,msg:"error",custom:JSON.stringify(item)+"tabs值需要为array类型"});	
			}				
			let res = await db.collection("xxm-bizhi-paper").add(arrs)
			return result({code:200,msg:"success",data:res});	
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});			
		}
	},
	
	
	
	
	//新增单个壁纸
	async addPaper({description,classid,copyright,picurl,tabs="[]",score=5,enable=true}){
		try{
			if(!classid) return result({code:400,msg:"required",custom:"必须传递classid"});
			if(!picurl) return result({code:400,msg:"required",custom:"必须传递picurl"});
			if(isNaN(score)) return result({code:400,msg:"error",custom:"score值需要为number类型"});
			score = Number(score);			
			tabs = JSON.parse(tabs);		
			if(!Array.isArray(tabs)) return result({code:400,msg:"error",custom:"tabs值需要为数组类型"});		
			let res = await db.collection("xxm-bizhi-paper").add({
				description,
				classid,
				copyright,
				picurl,
				tabs,
				score,
				enable,
				user_id:this.uid,
				createTime:Date.now(),
				updateTime:Date.now(),
				is_delete:false
			})
			return result({code:200,msg:"success",data:res});	
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});			
		}
	},
	
	//修改壁纸
	async updatePaper(){
		try{
			if(this.httpMethod!="POST") return result({code:400,msg:"error",custom:"method类型需要POST"});
			let {id,description,classid,copyright,picurl,tabs=[],score=5,enable=true} = this.body;
			if(!id) return result({code:400,msg:"required",custom:"必须传递id"});
			if(!classid) return result({code:400,msg:"required",custom:"必须传递classid"});
			if(!picurl) return result({code:400,msg:"required",custom:"必须传递picurl"});
			if(isNaN(score)) return result({code:400,msg:"error",custom:"score值需要为number类型"});					
			if(!Array.isArray(tabs)) return result({code:400,msg:"error",custom:"tabs值需要为数组类型"});	
							
			let res = await db.collection("xxm-bizhi-paper").doc(id).update({
				description,
				classid,
				copyright,
				picurl,
				tabs,
				score,
				enable,
				updateTime:Date.now()
			})
			if(res.updated) return result({code:200,msg:"success"});
			return result({code:400,msg:"error"});	
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});			
		}
	},
	
	//删除壁纸,支持批量删除
	async removePaper({ids=null}){		
		try{
			if(this.httpMethod!="DELETE") return result({code:400,msg:"error",custom:"method类型需要DELETE"});
			let {ids} = this.body;
			if(!ids) return result({code:400,msg:"required",custom:"必须传递ids"});
						
			
			let res = await db.collection("xxm-bizhi-paper").where({
				_id:dbCmd.in(ids)
			}).update({
				is_delete:true
			})			
			if(res.updated) return result({code:200,msg:"success"});
			return result({code:400,msg:"error"});
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});			
		}
	},
	
	
	
	
	//获取海报列表
	async banner({pageNum=1,pageSize=10}={}){
		try{
			if(this.httpMethod!="GET") return result({code:400,msg:"error",custom:"method类型需要GET"});			
			pageSize = pageSize>50 ? 50 : Number(pageSize);			
			let skipNum = (pageNum-1) * pageSize;	
			let whereObj = {is_delete:dbCmd.neq(true)};
					
			let res1 = db.collection("xxm-bizhi-banner")
			.where(whereObj)
			.orderBy("sort","asc")
			.skip(skipNum)
			.limit(pageSize)		
			.get();		
			
			let res2  = db.collection("xxm-bizhi-banner").where(whereObj).count();		
			let res = await Promise.all([res1,res2]);		
			return result({code:200,msg:"success",data:res[0].data,total:res[1].total});
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});			
		}		
	},
	
	
	
	//新增海报
	async addBanner(){
		try{
			if(this.httpMethod!="POST") return result({code:400,msg:"error",custom:"method类型需要POST"});
			let {url,picurl,sort,target="self",appid,enable=true} = this.body;			
			if(!url) return result({code:400,msg:"required",custom:"必须传递url"});
			if(!picurl) return result({code:400,msg:"required",custom:"必须传递picurl"});
			if(isNaN(sort)) return result({code:400,msg:"error",custom:"sort值需要为number类型"});
			let res = await db.collection("xxm-bizhi-banner").add({
				url,				
				picurl,
				sort,
				target,
				appid,
				user_id:this.uid,
				createTime:Date.now(),
				updateTime:Date.now(),
				enable,
				is_delete:false
			})
			return result({code:200,msg:"success",data:res});			
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});
		}
	},
	
	//修改海报
	async updateBanner(){		
		try{	
			if(this.httpMethod!="POST") return result({code:400,msg:"error",custom:"method类型需要POST"});
			let {id,url,picurl,sort,target="self",appid,enable=true} = this.body;
			
			if(!id) return result({code:400,msg:"required",custom:"必须传递id"});
			if(!url) return result({code:400,msg:"required",custom:"必须传递url"});
			if(!picurl) return result({code:400,msg:"required",custom:"必须传递picurl"});
			if(isNaN(sort)) return result({code:400,msg:"error",custom:"sort值需要为number类型"});
			
			let res = await db.collection("xxm-bizhi-banner").doc(id).update({
				url,				
				picurl,
				sort,
				target,
				appid,
				updateTime:Date.now(),
				enable
			})
			if(res.updated) return result({code:200,msg:"success"});
			return result({code:400,msg:"error"});	
			
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});
		}
	},
	
	
	
	
	//删除海报,支持批量删除
	async removeBanner(){		
		try{
			if(this.httpMethod!="DELETE") return result({code:400,msg:"error",custom:"method类型需要DELETE"});
			let {ids} = this.body;
			if(!ids) return result({code:400,msg:"required",custom:"必须传递ids"});
			let res = await db.collection("xxm-bizhi-banner").where({
				_id:dbCmd.in(ids)
			}).update({
				is_delete:true
			})			
			if(res.updated) return result({code:200,msg:"success",custom:`删除${res.updated}条`});
			return result({code:400,msg:"error",custom:`删除${res.updated}条`});
		}catch(e){
			return result({code:500,msg:"bug",custom:e.message});			
		}
	}
	
	
	
	
	
	
	
	
}
